﻿using MediatR;
using Microsoft.IdentityModel.Tokens; 
using PublicClass;
using S.Organization.Domian.Model;
using S.Organization.Infrastructure;
using S.Organization.Read.API.Application.Command.SupplierCommand;
using System.Security.Cryptography;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace S.Organization.Read.API.Application.CommandHandler.SupplierCommandHandler
{
    public class GetSupplierCommandHandler:IRequestHandler<GetSupplierCommand, PageInfo<Supplier>>
    {
        private readonly IBaseRepository<Supplier> _repository;


        public GetSupplierCommandHandler(IBaseRepository<Supplier> repository)
        {
            _repository = repository;
        }

        public async Task<PageInfo<Supplier>> Handle(GetSupplierCommand request, CancellationToken cancellationToken)
        {
            // request.SupplierNumber=DateTime.Now.ToString();
            var query = await _repository.AllAsync();
              
            PageInfo<Supplier> list = new PageInfo<Supplier>();
             
            //数据总条数
            list.totalCount = query.Count();
             
            //总页数
            list.pageCount = (int)Math.Ceiling(list.totalCount * 1.0 / (request.Size));
              
            //编号查询
            if (!string.IsNullOrEmpty(request.SupplierNumber))
            {
                query = query.Where(x => x.SupplierNumber == request.SupplierNumber);
            }
              
            //名称查询
            if (!string.IsNullOrEmpty(request.SupplierName))
            {
                query = query.Where(x=>x.SupplierName.Contains(request.SupplierName));
            }
              
             //负责人电话 
            if (!string.IsNullOrEmpty(request.PrincipalTelephone))
            {
                query = query.Where(x => x.PrincipalTelephone == request.PrincipalTelephone);
            }
              
            // 所属市场
            if (!string.IsNullOrEmpty(request.Market))
            {
                query = query.Where(x => x.Market == request.Market);
            }
             
            // 服务人员
            if (!string.IsNullOrEmpty(request.ServiceStaff))
            {
                query = query.Where(x => x.ServiceStaff == request.ServiceStaff);
            }
               
            // 归集档案
            if (!string.IsNullOrEmpty(request.CollectionFile))
            {
                query = query.Where(x => x.CollectionFile == request.CollectionFile);
            }
             
            // 使用状态
            if (request.UseOftate!=null)
            {
                query = query.Where(x => x.UseOftate == request.UseOftate);
            }
            query= query.OrderByDescending(x=>x.SupplierId);
            list.datas = query.Skip((request.Index-1)*request.Size).Take(request.Size).ToList(); 
            return list;

        }
    }
}
